package com.mercadoutils.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.Meli;
import com.mercadolibre.sdk.MeliException;
import com.mercadoutils.domain.Item;
import com.mercadoutils.listeners.SesionListener;
import com.mercadoutils.singletons.PoolConectionsSingleton;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;


@Controller
public class AddProductDataController {
	
	@RequestMapping("/addProductData.html")
	 public String doRedirect(@RequestParam("json") String jsonIds,Model model) throws AuthorizationFailure, ServletException, SQLException
	 {
		 HttpSession session = SesionListener.getSession();
		 Connection conexion = PoolConectionsSingleton.getConection();
		 Statement st = conexion.createStatement();
	     ResultSet rs;
	     rs = st.executeQuery("select id from currencies where country = (select country from muuser where id = "+session.getAttribute("userId")+") or country = 'Todos'");
	     String monedaRadioButton = "";
	     int i = 0;
	     while(rs.next()){
	    	 if(rs.getString("id").equals("EUR")||rs.getString("id").equals("USD"))
	    		 monedaRadioButton+="<label><input class=\"uniform\" type=\"radio\" id=\"moneda"+i+"\" name=\"moneda\" value=\""+rs.getString("id")+"\" disabled>"+rs.getString("id")+"</label>";
	    	 else
	    		 monedaRadioButton+="<label><input class=\"uniform\" type=\"radio\" id=\"moneda"+i+"\" name=\"moneda\" value=\""+rs.getString("id")+"\">"+rs.getString("id")+"</label>";
	    	 i++;
	     }
		 model.addAttribute("monedaRadioButton",monedaRadioButton);
		 model.addAttribute("jsonIdsVal",jsonIds);	
		 model.addAttribute("nombre",session.getAttribute("nombre"));
		 model.addAttribute("apellido",session.getAttribute("apellido"));
		 model.addAttribute("role",session.getAttribute("role"));
		 model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		 return "addProductData";
	 }
	
	@RequestMapping("/addProductDataPublish.html")
	 public String doPublish(Model model,@RequestParam(value="JsonIds") String jsonIds,
			                             @RequestParam(value="Category") String category,
			                             @RequestParam(value="tipoPublicacion") String listing_type_id,
			                             @RequestParam(value="moneda") String currency_id) throws AuthorizationFailure, ServletException, SQLException, MeliException, IOException
	 {
		JsonElement jelement = new JsonParser().parse(jsonIds); 
	    JsonObject  jobject = jelement.getAsJsonObject();
	    JsonArray jArray = jobject.getAsJsonArray("array");
	    Connection conexion = PoolConectionsSingleton.getConection();  
	    HttpSession session = SesionListener.getSession();
//    	session.getAttribute("userId")	    
	    Meli m = (Meli) session.getAttribute("meli");
	    //CAMBIAR LOS PARAMETROS SIGUIENTE PARA QUE NO SEAN ESTATICOS EN EL FUTURO
		String buying_mode = "buy_it_now";
		String video_id = null;
		String warranty = "12 meses";
		String pictures[] = new String[1];
		Statement st = conexion.createStatement();
        ResultSet rs;
	    for(int i=0;i<jArray.size();i++){
	    	jobject= jArray.get(i).getAsJsonObject();
	        rs = st.executeQuery("select title,subtitle,price,available_quantity,item_condition,description,picture from item where id="+jobject.get("id").toString());
	        rs.next();
	        pictures[0]="malditacomilla"+rs.getString("picture");
	        Item item = new Item(rs.getString("title"),rs.getString("subtitle"), rs.getDouble("price"),currency_id, rs.getInt("available_quantity"),
					buying_mode, category, rs.getString("description"), rs.getString("item_condition"), listing_type_id,
					video_id,warranty,pictures);
	        Gson gson = new Gson();
			String json = gson.toJson(item);
			
			json = json.replace("malditacomilla", "source\":\"");
			json = json.replace("[", "[{");
			json = json.replace("]", "}]");
			
			FluentStringsMap params = new FluentStringsMap();
			params.add("access_token", m.getAccessToken());
			Response r = m.post("/items", params,json);
			st.executeUpdate("update item set status='publicado' where id="+jobject.get("id").toString());
//			System.out.println(json);
			System.out.println(r.getResponseBody().toString());
	        
	        
	    }
//		System.out.println("jsonIds: "+jsonIds);
//		System.out.println("category: "+category);
//		System.out.println("description: "+descripcion);
//		System.out.println("tipo de publicacion: "+tipoPublicacion);
	    model.addAttribute("nombre",session.getAttribute("nombre"));
		model.addAttribute("apellido",session.getAttribute("apellido"));
		model.addAttribute("role",session.getAttribute("role"));
		model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		 return "redirect:/productListPendientes.html";
	 }


}
